<template>
  <TopSafeArea />
  <view class="container">
    <!-- 顶部Tab栏 -->
    <view class="tab-bar">
      <scroll-view class="tab-scroll" scroll-x>
        <view class="tab-item"
              :class="{ active: group.id === currentGroup?.id, dragging: groupDraggingId === group.id }"
              v-for="group in sortedGroups"
              :key="group.id"
              @click="switchGroup(group.id)"
              @longpress="longPressGroup(group)"
              @touchstart="handleGroupTouchStart(group.id, $event)"
              @touchmove="handleGroupTouchMove($event)"
              @touchend="handleGroupTouchEnd()"
              :style="{ transform: `translateX(${groupTranslateX[group.id] || 0}rpx)`, transition: groupTransition }">
          <text class="tab-text">{{ group.name }}</text>
        </view>
      </scroll-view>

      <view class="tab-actions">
        <uni-icons type="plus-filled" size="45" @click="addNewGroup" style="margin-right: 20rpx" color="#53d895"></uni-icons>
        <!--        <uni-icons type="gear" size="35" @click="goToSettings"></uni-icons>-->
      </view>
    </view>

    <!-- 物料列表 -->
    <view class="item-list">
      <Item
        v-for="item in currentItems"
        :key="item.id"
        :item="item"
        @delete="deleteItem"
        @move="moveItem"
        @calendarReminder="handleCalendarReminder"
        @edit="editItem"
      />
    </view>

    <!-- 底部新增按钮 -->
    <uni-icons type="plusempty" color="rgb(62, 107, 39)" class="add-button" size="50" @click="showAddItemModal"></uni-icons>

    <!-- 添加/编辑物料弹窗 -->
    <add-item ref="addItemPopup" />
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { type ItemGroup, type ItemType, useItemStore } from '@/stores/modules/item'
import { onLoad } from '@dcloudio/uni-app'
import Item from '@/components/Item.vue'
import AddItem from './add-item.vue'
import userCalendar from '@/hooks/userCalendar'

// 使用物料store
const itemStore = useItemStore()

// 页面加载时初始化
onLoad(() => {
  // 如果没有分组，添加默认分组
  if (itemStore.groups.length === 0) {
    itemStore.addGroup({ name: '默认分组', order: 0 })
  }
  if (currentItems.value.length === 0) {
    itemStore.addItemType({ name: '净水器滤芯', replacementCycle: 6, lastReplacementDate: new Date().toISOString(), groupId: 'default' })
  }
})

// 当前选中的分组
const currentGroup = computed<ItemGroup>(() => {
  return itemStore.groups.find(group => group.id === itemStore.currentGroupId) || itemStore.groups[0]
})

// 当前分组的物料列表
const currentItems = computed<ItemType[]>(() => {
  return itemStore.getCurrentGroupItems()
})

// 所有分组（按排序）
const sortedGroups = computed<ItemGroup[]>(() => {
  return [...itemStore.groups].sort((a, b) => a.order - b.order)
})


// 显示新增物料弹窗
const addItemPopup = ref(null)
const showAddItemModal = () => {
  if (addItemPopup.value) {
    addItemPopup.value.showAddPopup()
  }
}

// 编辑物料
const editItem = (item: ItemType) => {
  if (addItemPopup.value) {
    addItemPopup.value.showEditPopup(item)
  }
}

// 显示设置页面
const goToSettings = () => {
  uni.navigateTo({
    url: '/pages/index/settings',
  })
}

// 切换分组
const switchGroup = (groupId: string) => {
  itemStore.setCurrentGroup(groupId)
}

// 长按分组进行操作
const longPressGroup = (group: ItemGroup) => {
  // 显示操作菜单
  uni.showActionSheet({
    itemList: ['重命名', '删除'],
    success: function(res) {
      if (res.tapIndex === 0) {
        // 重命名
        renameGroup(group.id)
      } else if (res.tapIndex === 1) {
        // 删除
        deleteGroup(group)
      }
    },
  })
}

// 重命名分组
const renameGroup = (groupId: string) => {
  const group = itemStore.groups.find(g => g.id === groupId)
  if (!group) return

  uni.showModal({
    title: '重命名分组',
    editable: true,
    placeholderText: '请输入新的分组名称',
    success: function(res) {
      if (res.confirm) {
        const newName = res.content?.trim()
        if (newName) {
          itemStore.updateGroup(groupId, { name: newName })
          uni.showToast({
            title: '重命名成功',
            icon: 'success',
          })
        }
      }
    },
  })
}

// 删除分组
const deleteGroup = (group: ItemGroup) => {
  let groupId = group.id
  if (groupId === 'default') {
    uni.showToast({
      title: '默认分组不能删除',
      icon: 'none',
    })
    return
  }

  uni.showModal({
    title: '确认删除',
    content: `确定要删除${group.name}吗？`,
    success: function(res) {
      if (res.confirm) {
        itemStore.removeGroup(groupId)
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        })
        // 刷新页面
        switchGroup(sortedGroups.value[0].id)
      }
    },
  })
}

// 添加新分组
const addNewGroup = () => {
  // 这里实现添加新分组的逻辑
  // 在实际应用中，可以显示输入框让用户输入分组名称
  uni.showModal({
    title: '新增分组',
    editable: true,
    placeholderText: '请输入新的分组名称',
    success: function(res) {
      if (res.confirm) {
        let groupName = res.content?.trim()
        if (groupName) {
        } else {
          groupName = `分组${sortedGroups.value.length + 1}`
        }
        itemStore.addGroup({ name: groupName, order: sortedGroups.value.length })
        uni.showToast({
          title: '添加成功',
          icon: 'success',
        })
      }
    },
  })


}

// 删除物料
const deleteItem = (id: string) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个物料吗？',
    success: function(res) {
      if (res.confirm) {
        itemStore.removeItemType(id)
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        })
      }
    },
  })
}

// 处理日历提醒
const handleCalendarReminder = (item: any) => {
  // 添加日历提醒
  addCalendarReminder(item)
}
const { insertCalendar, deleteCalendar } = userCalendar()

// 添加日历提醒
const addCalendarReminder = (item: any) => {


  try {
    // 检查plus对象是否存在
    // if (typeof plus === 'undefined') {
    //   console.warn('plus not available')
    //   uni.showToast({
    //     title: '当前环境不支持日历提醒',
    //     icon: 'none',
    //     duration: 2000,
    //   })
    //   return
    // }
    // deleteCalendar(161)
    insertCalendar(item)


    // plus.calendar.create({
    //   title: `${item.name || '物料'}更换提醒`,
    //   description: `您的${item.name || '物料'}需要更换了`,
    //   startDate: formattedDate,
    //   endDate: formattedDate,
    //   alarm: {
    //     type: 'date',
    //     time: formattedDate,
    //     offset: 0,
    //   },
    // }, (event) => {
    //   console.log('日历事件创建成功', event)
    //   uni.showToast({
    //     title: `已添加日历提醒至${formattedDate}`,
    //     icon: 'success',
    //     duration: 2000,
    //   })
    // }, (error) => {
    //   console.error('日历事件创建失败', error)
    //   uni.showToast({
    //     title: '添加日历提醒失败',
    //     icon: 'none',
    //   })
    // })


    // #ifndef APP-PLUS
    // H5或其他平台使用提示
    uni.showToast({
      title: `已添加日历提醒至${formattedDate}`,
      icon: 'success',
      duration: 2000,
    })
    // #endif
  } catch (error) {
    console.error('添加日历提醒失败', error)
    uni.showToast({
      title: '添加日历提醒失败',
      icon: 'none',
    })
  }
}

// 移动物料（排序）
const moveItem = (id: string, direction: 'up' | 'down') => {
  // 获取当前分组的所有物料并按顺序排列
  const currentItems = itemStore.getCurrentGroupItems()
  const currentIndex = currentItems.findIndex(f => f.id === id)

  if (currentIndex === -1) return

  // 计算目标索引
  let targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1

  // 边界检查
  if (targetIndex < 0 || targetIndex >= currentItems.length) {
    uni.showToast({
      title: `已到达${direction === 'up' ? '顶部' : '底部'}`,
      icon: 'none',
    })
    return
  }

  // 交换位置
  const targetItem = currentItems[targetIndex]
  const currentItem = currentItems[currentIndex]

  // 更新排序
  const newOrder = targetItem.order
  targetItem.order = currentItem.order
  currentItem.order = newOrder

  // 更新store中的物料
  itemStore.updateItemType(targetItem.id, targetItem)
  itemStore.updateItemType(currentItem.id, currentItem)

  uni.showToast({
    title: `已${direction === 'up' ? '上' : '下'}移`,
    icon: 'success',
  })
}


// 分组拖拽相关状态
const groupDraggingId = ref<string | null>(null)
const groupStartX = ref(0)
const groupCurrentX = ref(0)
const groupTranslateX = ref<Record<string, number>>({})
const groupTransition = ref('none')

// 处理分组触摸开始
const handleGroupTouchStart = (groupId: string, e: TouchEvent) => {
  groupDraggingId.value = groupId
  groupStartX.value = e.touches[0].clientX
  groupCurrentX.value = groupStartX.value
  groupTransition.value = 'none'
}

// 处理分组触摸移动
const handleGroupTouchMove = (e: TouchEvent) => {
  if (!groupDraggingId.value) return

  groupCurrentX.value = e.touches[0].clientX
  const deltaX = groupCurrentX.value - groupStartX.value

  // 更新当前分组的位移
  groupTranslateX.value[groupDraggingId.value] = deltaX

  // 查找需要交换位置的分组
  const currentIndex = sortedGroups.value.findIndex(g => g.id === groupDraggingId.value)
  if (currentIndex === -1) return

  // 计算目标索引
  const itemWidth = 100 // 假设每个分组项宽度为100rpx
  const threshold = itemWidth / 2
  let targetIndex = currentIndex

  if (Math.abs(deltaX) > threshold) {
    if (deltaX > 0) {
      targetIndex = Math.min(currentIndex + 1, sortedGroups.value.length - 1)
    } else {
      targetIndex = Math.max(currentIndex - 1, 0)
    }
  }

  // 如果需要交换位置，更新排序
  if (targetIndex !== currentIndex) {
    const newGroups = [...sortedGroups.value]
    const [movedGroup] = newGroups.splice(currentIndex, 1)
    newGroups.splice(targetIndex, 0, movedGroup)

    // 更新所有分组的order值
    newGroups.forEach((group, index) => {
      itemStore.updateGroup(group.id, { order: index })
    })

    // 更新起始位置
    groupStartX.value = groupCurrentX.value
  }
}

// 处理分组触摸结束
const handleGroupTouchEnd = () => {
  if (!groupDraggingId.value) return

  // 重置状态
  groupTranslateX.value[groupDraggingId.value] = 0
  groupTransition.value = 'transform 0.3s'
  groupDraggingId.value = null

  setTimeout(() => {
    groupTransition.value = 'none'
  }, 300)
}
</script>

<style lang="scss">
.container {
  height: calc(100vh - 70rpx);
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  margin-top: 30rpx;
}

.tab-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 7vh;
  padding: 10rpx 20rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #e0e0e0;
}

.tab-scroll {
  white-space: nowrap;
  width: calc(100% - 60rpx);
}

.tab-item {
  display: inline-block;
  padding: 8rpx 15rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
  transition: transform 0.2s, background-color 0.2s;

  &.active {
    background: radial-gradient(#26d899, rgba(46, 204, 113, 0.75));

    .tab-text {
      color: #ffffff;
    }
  }

  &.dragging {
    background-color: #e0e0e0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
  }
}

.tab-text {
  font-size: 40rpx;
  font-weight: 500;
}

.tab-actions {
  display: flex;
  gap: 15rpx;

  .iconfont {
    font-size: 20rpx;
    color: #333333;
  }
}

.item-list {
  flex: 1;
  overflow-y: auto;
  padding: 10rpx;
}


.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}


.item-countdown {
  flex: 3;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
  color: #27ba9b;
}

.item-actions {
  flex: 2;
  display: flex;
  justify-content: flex-end;

  .iconfont {
    font-size: 20rpx;
    color: #27ba9b;
  }
}

.add-button {
  position: fixed;
  bottom: 10vh;
  left: 50%;
  transform: translateX(-50%);
  width: 35vw;
  height: 35vw;
  border-radius: 50%;
  background: radial-gradient(#26d899, rgba(46, 204, 113, 0.75));
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);

}
</style>
